import torch
import torch.nn as nn
from ResNestBottleneck import ResNestBottleneck  

class ResNeSt(nn.Module):
    def __init__(self, block, layers, num_classes=100, radix=2, cardinality=1,
                 base_width=64, stem_width=64, deep_stem=True,
                 avg_down=True, avd=True, avd_first=False):
        super(ResNeSt, self).__init__()
        self.cardinality = cardinality
        self.base_width = base_width
        self.radix = radix
        self.avd = avd
        self.avd_first = avd_first

        # CIFAR 数据集使用简化的 stem
        if deep_stem:
            self.conv1 = nn.Sequential(
                nn.Conv2d(3, stem_width, kernel_size=3, stride=1, padding=1, bias=False),
                nn.BatchNorm2d(stem_width),
                nn.ReLU(inplace=True),
                nn.Conv2d(stem_width, stem_width, kernel_size=3, stride=1, padding=1, bias=False),
                nn.BatchNorm2d(stem_width),
                nn.ReLU(inplace=True),
                nn.Conv2d(stem_width, stem_width*2, kernel_size=3, stride=1, padding=1, bias=False),
            )
        else:
            self.conv1 = nn.Conv2d(3, stem_width*2, kernel_size=3, stride=1, padding=1, bias=False)
        
        self.bn1 = nn.BatchNorm2d(stem_width*2)
        self.act1 = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
        
        # 构建网络层
        self.inplanes = stem_width*2
        self.layer1 = self._make_layer(block, 64, layers[0], avg_down=avg_down)
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2, avg_down=avg_down)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2, avg_down=avg_down)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2, avg_down=avg_down)
        
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        # 权重初始化
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, planes, blocks, stride=1, avg_down=False):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            if avg_down:
                downsample = nn.Sequential(
                    nn.AvgPool2d(stride, stride=stride, ceil_mode=True, count_include_pad=False),
                    nn.Conv2d(self.inplanes, planes * block.expansion, 
                              kernel_size=1, stride=1, bias=False),
                    nn.BatchNorm2d(planes * block.expansion)  
                )
            else:
                downsample = nn.Sequential(
                    nn.Conv2d(self.inplanes, planes * block.expansion,
                              kernel_size=1, stride=stride, bias=False),
                    nn.BatchNorm2d(planes * block.expansion)
                )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample,
                            radix=self.radix, cardinality=self.cardinality,
                            base_width=self.base_width, avd=self.avd, 
                            avd_first=self.avd_first, is_first=True))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes,
                                radix=self.radix, cardinality=self.cardinality,
                                base_width=self.base_width, avd=self.avd,
                                avd_first=self.avd_first))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.act1(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)

        return x
